package service_statistics

import (
	"fmt"
	"time"
	"tools-api/src/common/db/database"
	"tools-api/src/jcj/model"

	"github.com/gin-gonic/gin"
	"xorm.io/xorm"
)

// GetBillList 年账单/月账单
// _type 账单类型
// - 1 年账单
// - 2 月账单
func GetBillList(uuid string, book model.Book, _type, year, monthStart int) []map[string]interface{} {
	var result []map[string]interface{}
	if _type == 2 {
		result = model.StatisticsBill{}.GroupByMonth(uuid, book.Id, -1, year, monthStart)
	} else {
		result = model.StatisticsBill{}.GroupByYear(uuid, book.Id, -1, monthStart)
	}
	for i := 0; i < len(result); i++ {
		item := result[i]
		if item["type"].(int64) == 1 {
			item["book_name"] = book.Name // 添加账本名字
			break
		}
	}
	tip := gin.H{"type": 2}
	if len(result) == 1 { // 空数据
		tip["title"] = "还没有记账哦~"
	} else {
		if _type == 2 {
			tip["title"] = fmt.Sprintf("月账单日为 (%d日)", monthStart)
		} else {
			if monthStart == 1 {
				tip["title"] = "年账单为 (1.1-12.31)"
			} else {
				tip["title"] = fmt.Sprintf("年账单为 (1.%d-次年1.%d)", monthStart, monthStart-1)
			}
		}
	}
	result = append(result, tip)
	return result
}

// GetBillListByAccount 年账单/月账单 （收支账户）
// _type 账单类型
// - 1 年账单
// - 2 月账单
func GetBillListByAccount(uuid string, book model.Book, account model.BookAccounts, _type, year int) []map[string]interface{} {
	var result []map[string]interface{}
	if _type == 2 {
		result = model.StatisticsBill{}.GroupByMonth(uuid, book.Id, account.Id, year, account.MonthStart)
	} else {
		result = model.StatisticsBill{}.GroupByYear(uuid, book.Id, account.Id, account.MonthStart)
	}
	for i := 0; i < len(result); i++ {
		item := result[i]
		if item["type"].(int64) == 1 {
			item["book_name"] = book.Name + "：" + account.Name // 添加账本名字
			break
		}
	}
	tip := gin.H{"type": 2}
	if len(result) == 1 { // 空数据
		tip["title"] = "还没有记账哦~"
	} else {
		if _type == 2 {
			tip["title"] = fmt.Sprintf("月账单日为 (%d日)", account.MonthStart)
		} else {
			if account.MonthStart == 1 {
				tip["title"] = "年账单为 (1.1-12.31)"
			} else {
				tip["title"] = fmt.Sprintf("年账单为 (1.%d-次年1.%d)", account.MonthStart, account.MonthStart-1)
			}
		}
	}
	result = append(result, tip)
	return result
}

// generateDateRange 生成从start到end的所有日期
func generateDateRange(start, end string) []string {
	var dates []string
	current, _ := time.Parse("2006-01-02", start)
	endDay, _ := time.Parse("2006-01-02", end)

	for !current.After(endDay) {
		dates = append(dates, current.Format("2006-01-02"))
		current = current.AddDate(0, 0, 1)
	}

	return dates
}

// GetBillDailyInfos 获取每日收支
func GetBillDailyInfos(uuid string, bookId int64, start, end string) gin.H {
	// 每日收支
	dailyList := getBillDailyList(uuid, bookId, start, end)
	// 类别支出(排行榜)
	payoutRank := model.StatisticsBill{}.GetMonthGroupByTypes(uuid, bookId, start, end, 1)
	// 类别收入(排行榜)
	incomeRank := model.StatisticsBill{}.GetMonthGroupByTypes(uuid, bookId, start, end, 2)
	// 类别支出(排行榜)
	payoutDetailRank := model.StatisticsBill{}.GetMonthRank10(uuid, bookId, start, end, 1)
	// 类别收入(排行榜)
	incomeDetailRank := model.StatisticsBill{}.GetMonthRank10(uuid, bookId, start, end, 2)
	return gin.H{
		"daily":              dailyList,
		"types_rank_payout":  payoutRank,
		"types_rank_income":  incomeRank,
		"detail_rank_payout": payoutDetailRank,
		"detail_rank_income": incomeDetailRank,
	}
}
func getBillDailyList(uuid string, bookId int64, start, end string) []model.StatisticsBillDay {
	dates := generateDateRange(start, end)
	list := model.StatisticsBill{}.GetDailyList(uuid, bookId, start, end)
	// 转换为map便于匹配
	dataMap := make(map[string]model.StatisticsBillDay)
	for _, item := range list {
		dataMap[item.Date] = item
	}
	result := make([]model.StatisticsBillDay, 0)
	for _, date := range dates {
		if item, exists := dataMap[date]; exists {
			result = append(result, item)
		} else {
			result = append(result, model.StatisticsBillDay{Date: date, Income: 0, Payout: 0})
		}
	}
	return result
}

// GetBillDetailByTypes 类别排行榜明细
func GetBillDetailByTypes(uuid string, bookId, typesId int64, start, end string) []model.BookDetailResult {
	list := make([]model.BookDetailResult, 0) // []string{"user_db.user", "u"}
	_ = database.Session(database.JCJEngine.NewSession(), func(session *xorm.Session) error {
		// 同一个session中获取列表、数量
		list = model.BookDetail{}.GetListByUuid(session, uuid, bookId, typesId, start, end)
		return nil
	})
	return list
}
